package cn.wowjoy.office.applystock;

import android.arch.lifecycle.Observer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.bingoogolapple.badgeview.BGABadgeTextView;
import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.event.CountEvent;
import cn.wowjoy.office.data.event.StorageCodeEvent;
import cn.wowjoy.office.data.response.ApplyHeadInfoResponse;
import cn.wowjoy.office.data.response.ApplyHeadListResponse;
import cn.wowjoy.office.databinding.FragmentStayOutStockBinding;
import cn.wowjoy.office.utils.TextUtil;

/**
 * A simple {@link NewBaseFragment} subclass.
 * Use the {@link StayOutStockFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class StayOutStockFragment extends NewBaseFragment<FragmentStayOutStockBinding,ApplyStockViewModel> {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String STATUS = "status";
    private static final String STORAGECODE = "storagecode";
    private static final String TYPE = "type";

    // TODO: Rename and change types of parameters
    private String status;
    private String storageCode;
    private MDialog waitDialog;
    private boolean isFirstGet = false;
    private int type;

    private boolean isRequisition;

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }
    public StayOutStockFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param status Parameter 1.
     * @param type Parameter 2.
     * @return A new instance of fragment StayOutStockFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static StayOutStockFragment newInstance(String status, int type) {
        StayOutStockFragment fragment = new StayOutStockFragment();
        Bundle args = new Bundle();
        args.putString(STATUS, status);
        args.putInt(TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    public void setStorageCode(String storageCode) {
        this.storageCode = storageCode;
        viewModel.setStroageCode(storageCode);
//        viewModel.getList(true);
    }

    @Override
    protected Class<ApplyStockViewModel> getViewModel() {
        return ApplyStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_stay_out_stock;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            status = getArguments().getString(STATUS);
            type = getArguments().getInt(TYPE);
        }
        viewModel.setStatus(status);
        viewModel.setType(type);
        viewModel.setIsEnd(null);
        viewModel.setCanCreate(true);

    }
    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.flError;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(storageCode))
            viewModel.getList(true);

    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        initData();
        initView();
        initObserve();
    }
    private void initData(){
        switch (type){
            case Constants.RECEIPTS_CODE_APPLY:
                isRequisition = false;
                break;
            case Constants.RECEIPTS_CODE_APPLY_FOR:
                isRequisition = false;
                break;
            case Constants.RECEIPTS_CODE_ALLOT:
                isRequisition = true;
                break;
        }


    }
    public void initView(){
        binding.emptyView.emptyContent.setText("没有待出库的申领单");
        binding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rv.setAdapter(viewModel.lAdapter);
        binding.rv.addItemDecoration(new SimpleItemDecoration(getActivity(),SimpleItemDecoration.VERTICAL_LIST));
        binding.rv.setEmptyView(binding.emptyView.getRoot());
        binding.rv.setLoadMoreEnabled(true);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StorageCodeEvent event) {
        if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(event.getStorageCode())){
            viewModel.setStroageCode(event.getStorageCode());
            viewModel.getList(true);
        }
    }
    public void initObserve(){
        viewModel.reponses.observe(this, new Observer<LiveDataWrapper<ApplyHeadListResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ApplyHeadListResponse> applyHeadListResponseLiveDataWrapper) {
                switch (applyHeadListResponseLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        clearDialog();
                        int count = 0;
                        if (isRequisition)
                            count = applyHeadListResponseLiveDataWrapper.data.getCount();
                        else
                            count = applyHeadListResponseLiveDataWrapper.data.getTotalCount();
                        EventBus.getDefault().post(new CountEvent(count));
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(applyHeadListResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });

    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(storageCode)){
            isFirstGet = true;
            viewModel.getList(true);
        }

    }

    @Override
    protected void onStartLazy() {
        super.onStartLazy();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    protected void onStopLazy() {
        super.onStopLazy();
        EventBus.getDefault().unregister(this);
    }


}
